package chat.keepWind.event;

import java.net.InetSocketAddress;

import chat.keepWind.handle.KeepWindDecoder;
import chat.keepWind.handle.KeepWindEncoder;
import chat.keepWind.handle.KeepWindInboundHandler;
import chat.keepWind.util.GlobalConst;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class ReceiveDataPackage {
	
	public void listen() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(65535))
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new KeepWindDecoder()); //解密
                            pipeline.addLast(new KeepWindEncoder(null)); //编码
                            pipeline.addLast(new KeepWindInboundHandler());//处理数据
                            
                        }
                    })
                    .localAddress(new InetSocketAddress(GlobalConst.RCV_PORT));
            
            Channel channel = bootstrap.bind().syncUninterruptibly().channel();
            
            channel.closeFuture().await();
            
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
	
	public static void main(String[] args) {
		System.out.println("开启服务");
		new ReceiveDataPackage().listen();
	}
}
